package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 提交訂單
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
//        查詢收穫地址是否存在
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

//        檢查用戶的收穫地址是否超出範圍
        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());

//        查詢購物車裏是否存在商品
        Long userId = BaseContext.getCurrentId(); // 獲取用戶id
        ShoppingCart shoppingCart = ShoppingCart.builder().build();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.getList(shoppingCart); // 獲得購物車信息
        if (shoppingCartList.size() == 0 || shoppingCartList == null) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

//        創建訂單實體類
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setUserId(userId);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        orderMapper.submit(order); //  將訂單數據插入數據庫表中


//        創建一個 OrderDetail 類型的集合
        List<OrderDetail> detailList = new ArrayList<>();

        shoppingCartList.forEach(shoppingCart1 -> {
            OrderDetail orderDetail = OrderDetail.builder().build();
            BeanUtils.copyProperties(shoppingCart1, orderDetail);

            orderDetail.setOrderId(order.getId());

            detailList.add(orderDetail);
        });

        orderDetailMapper.insert(detailList);

        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().id(userId).orderNumber(order.getNumber()).orderAmount(order.getAmount()).orderTime(LocalDateTime.now()).build();


//        訂單提交后清空購物車的信息
        shoppingCartMapper.deleteByUserId(userId);

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public void payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        HashMap map = new HashMap();
        map.put("type", 1);
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号" + ordersDB.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 查詢歷史訂單
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO)  {
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());

        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO); // 查詢返回一個訂單集合

        List<OrderVO> orderVOList = new ArrayList<>(); // 創建訂單返回包裝類集合

//        根據訂單集合來
        if (page != null && page.getTotal() > 0) {
            page.forEach(orderVO -> {
                Long orderVOId = orderVO.getId();
                orderDetailMapper.getByOrdersId(orderVOId);
            });
            page.forEach( orders -> {
                Long ordersId = orders.getId(); // 獲取訂單Id
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrdersId(ordersId); // 獲取訂單詳細信息

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);

                orderVOList.add(orderVO);
            });
        }

        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 查看訂單詳情
     * @param id
     * @return
     */
    @Override
    public OrderVO getDetails(Long id) {
        Orders order = orderMapper.getByOrderId(id); // 根據訂單id查詢訂單

        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrdersId(id); // 根據訂單id查詢訂單的詳細數據

        OrderVO orderVO = new OrderVO();

        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(orderDetailList);


        return orderVO;
    }

    /**
     * 取消訂單
     * @param id
     * @throws Exception
     */
    @Override
    public void cancelById(Long id) throws Exception {
        /**
         * 獲取訂單
         * 判斷訂單是否存在
         * 檢驗訂單轉臺
         * 進行退款操作
         */

        Orders orders = orderMapper.getByOrderId(id);

//        判斷訂單是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if (orders.getStatus() > 2) {
            throw  new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders1 = new Orders();
        orders1.setId(orders.getId());

        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
//            weChatPayUtil.refund(orders.getNumber(), orders.getNumber(), new BigDecimal(0.01), new BigDecimal(0.01));

            orders1.setPayStatus(Orders.REFUND); // 插入退款狀態

        }

        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelReason("用户取消");
        orders1.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders1);
    }

    /**
     * 再來一單
     * @param id
     */
    @Override
    public void addAgain(Long id) {

        List<OrderDetail> orderDetails = orderDetailMapper.getByOrdersId(id); // 獲取訂單詳情

        // 將訂單詳情轉換爲購物車
        List<ShoppingCart> shoppingCarts = orderDetails.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;

        }).collect(Collectors.toList());

        shoppingCartMapper.addBatch(shoppingCarts);
    }

    /**
     * 條件查詢
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult searchByCondition(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = getOrderVoList(ordersPage);

        return new PageResult(ordersPage.getTotal(), orderVOList);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO getByStatistics() {
        Long userId = BaseContext.getCurrentId(); // 獲得當前用戶Id

        Integer confirmed = orderMapper.getByStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.getByStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer toBeConfirmed = orderMapper.getByStatus(Orders.TO_BE_CONFIRMED);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);


        return orderStatisticsVO;
    }


    /**
     * 接單
     * @param ordersConfirmDTO
     */
    @Override
    public void Ordering(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder().build();

        orders.setId(ordersConfirmDTO.getId());

        orders.setStatus(Orders.CONFIRMED); // 將狀態改爲已接單

        orderMapper.update(orders);
    }

    /**
     * 商家拒單
     * @param ordersRejectionDTO
     */
    @Override
    public void Declines(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        Orders orders = orderMapper.getByOrderId(ordersRejectionDTO.getId()); // 根據訂單id查詢訂單

        // 判斷訂單狀態,儅訂單存在且訂單狀態為待支付時，可以拒單
        if (orders == null || orders.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 判斷訂單的支付狀態，已付款就調用微信接口退錢，未付款直接修改狀態
        if (orders.getPayStatus() == Orders.PAID ) {
//            String refund = weChatPayUtil.refund(orders.getNumber(), orders.getNumber(), new BigDecimal(0.01), new BigDecimal(0.01));
            log.info("調用微信退款接口：");
        }

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());

        orderMapper.update(orders);
    }


    /**
     * 商家取消訂單
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getByOrderId(ordersCancelDTO.getId());

        if (orders == null || orders.getStatus() == Orders.COMPLETED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        if (orders.getPayStatus() == Orders.PAID ) {

            log.info("調用微信退款接口：{}");
        }


        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);

        orderMapper.update(orders);
    }


    /**
     * 商家派送訂單
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        if (orders == null || orders.getStatus() != Orders.CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }


    /**
     * 商家完成訂單
     * @param id
     */
    @Override
    public void complete(Long id) {

        Orders orders = orderMapper.getByOrderId(id);
        if (orders == null || orders.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }


        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        if (orders == null && orders.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", orders.getId());
        map.put("content", "订单号" + orders.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


    private void checkOutOfRange(String address) {

        Map map = new HashMap();
        map.put("address",shopAddress); //商铺的地址
        map.put("output","json"); //返回json格式
        map.put("ak",ak); //appkey 百度平台中复制

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;



        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

    private List<OrderVO> getOrderVoList(Page<Orders> ordersPage) {
        List<Orders> ordersList = ordersPage.getResult();

        List<OrderVO> orderVOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(ordersList)) {
           ordersList.forEach(orders -> {
               OrderVO orderVO = new OrderVO();
               BeanUtils.copyProperties(orders, orderVO);

               String orderDishes = getOrderDishesStr(orders);

               orderVO.setOrderDishes(orderDishes);
               orderVOList.add(orderVO);
           });
        }
        return orderVOList;
    }

    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrdersId(orders.getId());

        List<String> orderDishList = orderDetailList.stream().map(orderDetail -> {
            String orderDish = orderDetail.getName() + "*" + orderDetail.getNumber() + ";";  // 拼接字符串
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

}
